package services

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	utils "hft/Http/Utils"
	"hft/global"
	"hft/tools"
)

type HomeSwiper struct{}

func (*HomeSwiper) GeArticleList(claims tools.BaseClaims) (data []*admin.ArticleBase, err error) {

	var account *admin.Account

	var list []*admin.ArticleBase

	global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account)

	global.OC_DB.Where("region_link LIKE ?", fmt.Sprintf("%%%v", account.RegionLink)).Find(&list)

	return list, nil
}

func (*HomeSwiper) CreateSwiper(claims tools.BaseClaims, data *admin.HomeSwiper) (err error) {

	var account *admin.Account

	var city []*admin.Region

	global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account)

	ids := utils.BeLongCity(account.RegionLink)

	global.OC_DB.Where("level = ?", "city").Find(&city, ids)

	if len(city) == 0 {
		return errors.New("未知错误500")
	}

	data.RegionLink = account.RegionLink
	data.City = int(city[0].ID)

	global.OC_DB.Model(&admin.HomeSwiper{}).Create(&data)

	return nil

}

func (*HomeSwiper) GetSwiper(claims tools.BaseClaims, origin int) (list []*admin.HomeSwiper, err error) {

	var account *admin.Account

	global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account)

	var newList []*admin.HomeSwiper

	global.OC_DB.Scopes(dao.HomeSwiperDao.GetSwiperList(origin, global.OC_DB)).Omit("region_link,region,create_time").Order("sort desc").Where("region_link LIKE ?", fmt.Sprintf("%v%%", account.RegionLink)).Find(&newList)

	return newList, nil
}

func (*HomeSwiper) Delete(ids []int, claims tools.BaseClaims) (err error) {

	var account *admin.Account

	global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account)

	var list []*admin.HomeSwiper

	global.OC_DB.Find(&list, ids)

	if !utils.IsSwiperBelongThisRegion(list, account.RegionLink) {
		return errors.New("你无权管理该地区轮播图")
	}

	global.OC_DB.Unscoped().Delete(&list)

	return nil

}

var HomeSwiperService = new(HomeSwiper)
